<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\AclUser;
use ffhome\common\util\CommonUtil;
use think\facade\Db;

class Index extends CommonController
{
    /**
     * 后台主页
     */
    public function index()
    {
        $this->app->view->engine()->layout(false);
        return $this->fetch();
    }

    /**
     * 欢迎页
     */
    public function welcome()
    {
        return $this->fetch();
    }

    /**
     * 修改人员信息
     */
    public function editUser()
    {
        $id = currentUserId();
        $row = Db::name(AclUser::MODEL_NAME)->withoutField('password')->find($id);
        empty($row) && $this->error(lang('common.data_not_exist'));
        if (!$this->request->isAjax()) {
            $this->assign('row', $row);
            return $this->fetch();
        }
        $param = $this->request->only(['nickname', 'mobile', 'avatar']);
        $param['id'] = $id;
        $param['update_by'] = $id;
        $param['update_time'] = date('Y-m-d H:i:s');
        Db::name(AclUser::MODEL_NAME)->update($param);
        $this->success(lang('common.save_success'));
    }

    /**
     * 修改密码
     */
    public function editPassword()
    {
        $id = currentUserId();
        $row = Db::name(AclUser::MODEL_NAME)->find($id);
        if (!$row) {
            $this->error(lang('common.data_not_exist'));
        }
        if (!$this->request->isAjax()) {
            $this->assign('row', $row);
            return $this->fetch();
        }
        $param = $this->request->only(['password', 'password_new', 'password_again']);
        $rule = [
            'password|' . lang('user.password') => 'require',
            'password_new|' . lang('user.password_new') => 'require',
            'password_again|' . lang('user.password_again') => 'require',
        ];
        $this->validate($param, $rule);
        if ($param['password_new'] != $param['password_again']) {
            $this->error(lang('user.password_not_equal'));
        }
        if ($row['password'] != CommonUtil::password($param['password'])) {
            $this->error(lang('user.password_error'));
        }
        Db::name(AclUser::MODEL_NAME)->update(['id' => $id, 'password' => CommonUtil::password($param['password_new'])]);
        $this->success(lang('user.password_success'));
    }
}
